﻿using System;
using System.Collections.ObjectModel;
using System.Data.Services.Client;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using Namespace;

namespace Demo.TableStorageDataServices.WP7
{
    public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
    {
        private readonly ObservableCollection<Enigma> _enigmas = new ObservableCollection<Enigma>();
        public ObservableCollection<Enigma> Enigmas
        {
            get { return _enigmas; }
        }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += (sender, e) => this.DataContext = this;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                //var container = new Container(new Uri("http://wwzeclouddemo100511.cloudapp.net/Services/DemoDataService.svc"));
                var container = new Container(new Uri("http://127.0.0.1:81/Services/DemoDataService.svc"));

                var enigmas = new DataServiceCollection<Enigma>(container);

                enigmas.LoadCompleted += (sender, ev) =>
                                             {
                                                 if (ev.Error != null) return;
                                                 if (enigmas.Continuation != null)
                                                 {
                                                     enigmas.LoadNextPartialSetAsync();
                                                 }
                                                 else
                                                 {
                                                     this.DataContext = enigmas;
                                                 }
                                             };
                enigmas.LoadAsync(new Uri("/Enigmas", UriKind.Relative));

            }
            catch (Exception ex)
            {
                
            }
            base.OnNavigatedTo(e);
        }

        private void AddEnigmaClick(object sender, System.EventArgs e)
        {
            Uri navigateUri = new Uri("/AddEnigmaPage.xaml", UriKind.Relative);
            NavigationService.Navigate(navigateUri);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName)) return;

            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}